package org.example;

import bean.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

//import javax.annotation.Resources;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class TestMybatis {
    public static void main(String[] args) {
        /*创建输入流*/
        InputStream inputStream = null;
        /*将MyBatis配置文件转化为输入流*/
        try {
            String resource = "mybatis.xml";
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        /*通过SqlSessionFactoryBuilder创建SqlSessionFactory对象*/
        SqlSessionFactory build =
                new SqlSessionFactoryBuilder().build(inputStream);
        /*通过SqlSessionFactory创建SqlSession对象*/
        SqlSession sqlSession = build.openSession();
        //System.out.println(sqlSession);
        List<User> users = sqlSession.selectList("user.selectUser");
        /*将返回值输出*/
        for (User u : users) {
            System.out.println(u);
        }
        //插入
        User u1 = new User("嘻嘻","123","19");
        int row1 = sqlSession.insert("user.addUser",u1);
        if (row1 == 1){
            System.out.println("插入成功");
            sqlSession.commit();
        }
        else{
            System.out.println("插入失败");
            sqlSession.rollback();
        }
        User u2 = new User("zz","123","17");
        int row2 = sqlSession.update("user.deleteUser",u2);
        if (row2 == 1){
            System.out.println("删除成功");
            sqlSession.commit();
        }
        else{
            System.out.println("删除失败");
            sqlSession.rollback();
        }
        User u3 = new User("王五","123","33");
        int row3 = sqlSession.update("user.updateUser",u3);
        if (row3 == 1){
            System.out.println("修改成功");
            sqlSession.commit();
        }
        else{
            System.out.println("修改失败");
            sqlSession.rollback();
        }
        /*关闭事务*/
        sqlSession.close();
    }
}
